<template>
  <el-dialog
    v-loading="loading"
    custom-class="add-spu-dialog"
    top="10vh"
    :visible.sync="dialogVisible"
    width="1040px"
    :destroy-on-close="true"
    :before-close="handleClose"
  >
    <add-spu-search-head v-if="!isVerification" ref="addSpuSearchHeadRef" :search-data="searchData" @search="search" @reset="search(true)" />

    <ess-table
      ref="essTableRef"
      size="mini"
      :external-height="20"
      :thead-list="theadList"
      :data-list="dataList"
      :page-size-list="pageSizeList"
      :total="total"
      :count-height="false"
      :container-box="containerBox"
      :other-container-box="otherContainerBox"
      :pagination-show="!isVerification"
      :selectable="selectable"
      @handleCurrentChange="handleCurrentChange"
      @handleSizeChange="handleSizeChange"
      @selectionChange="selectionChange"
    >
      <template v-slot:spuId="{ scope }"> {{ scope.row.spuCode || scope.row.spuId || '' }}</template>

      <el-button
        v-if="!isAddUpc"
        slot="right"
        class="send-spu"
        size="mini"
        type="primary"
        icon="el-icon-s-promotion"
        :disabled="!multipleSelection.length > 0"
        :loading="verificationStatus"
        round
        @click="writeSpuName"
      >
        {{ verificationStatus ? '校验中' : '发起SPU' }}
      </el-button>

      <el-button
        v-if="isAddUpc"
        slot="right"
        class="send-spu"
        size="mini"
        type="primary"
        icon="el-icon-s-promotion"
        :disabled="multipleSelection.length !== 1"
        round
        @click="addUpc"
      >
        添加UPC
      </el-button>
    </ess-table>

    <wirte-spu-name
      ref="wirteSpuNameRef"
      :form-data="formData"
      @sendSpuSuccess="
        () => {
          isrefresh = true
          $refs.essTableRef.setHeight()
          verificationInfo()
        }
      "
    />
  </el-dialog>
</template>

<script>
import addSpuSearchHead from './addSpuSearchHead.vue'
import essTable from '@/components/eTable/eTable.vue'
import wirteSpuName from './wirteSpuName.vue'
import { addSpuList } from '@/views/coi/commonJs/tableHeadList.js'
import { addSpuListData, getVerificationInfo, addSpuSkuMapping } from '@/api/coi/onlineTaskAPI/spu.js'
import { addChgSpuSkuMapping } from '@/api/coi/onlineTaskAPI/spuEdit.js'
import { stringToArray } from '@/utils/processingData'

export default {
  name: 'AddSPU',
  components: {
    addSpuSearchHead,
    essTable,
    wirteSpuName
  },
  props: {
    isAddUpc: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: ''
    },
    skuInfoList: {
      type: Array,
      default() {
        return []
      }
    },
    spuId: {
      type: [Number, String, null],
      default: null
    },
    menuName: {
      type: String,
      default: ''
    },
    increased: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      dialogVisible: false,
      loading: false,
      dataList: [],
      total: 0,
      containerBox: '.add-spu-dialog .el-dialog__body',
      otherContainerBox: ['.add-spu-dialog .add-spu-head'],
      searchData: {},
      theadList: addSpuList(this.isAddUpc),
      pageSizeList: [10, 20, 50],
      multipleSelection: [],
      formData: {
        remark: '',
        spuName: '',
        upcList: []
      },
      interval: null,
      verificationStatus: false,
      isVerification: false,
      isrefresh: false
    }
  },
  watch: {
    dialogVisible(v) {
      if (v) {
        this.$nextTick(() => {
          this.initalData()
          this.$refs.essTableRef.createAutoSetHeight()
        })
      } else {
        if (this.interval) window.clearInterval(this.interval)
        this.interval = null
        this.$refs.essTableRef.closeAutoSetHeight()
      }
    }
  },
  beforeDestroy() {
    if (this.interval) window.clearInterval(this.interval)
  },
  methods: {
    initalData() {
      const searchData = {
        pageNum: 1,
        pageSize: 10
      }
      this.searchData = searchData
    },
    selectable({ skuType, spuId, spuCode }) {
      return Boolean(!spuId && !spuCode && skuType === '2')
    },
    handleClose() {
      this.isVerification = false
      this.verificationStatus = false
      this.dataList = []
      this.formData = {
        spuName: '',
        remark: '',
        upcList: []
      }
      this.total = 0
      this.$refs.essTableRef.tableHeight = 0
      this.$refs.essTableRef.clearSelection()
      this.isrefresh && this.$parent && this.$parent.search && this.$parent.search()
      this.isrefresh = false
      this.dialogVisible = false
    },
    handleCurrentChange(val) {
      this.searchData.pageNum = val
      this.queryData()
    },
    handleSizeChange(val) {
      this.searchData.pageSize = val
      this.handleCurrentChange(1)
    },
    handleData() {
      const searchData = JSON.parse(JSON.stringify(this.searchData))
      if ('upcNbrList' in searchData) searchData.upcNbrList = stringToArray(searchData.upcNbrList, /[\n\r]/)
      if ('upcWoCdList' in searchData) searchData.upcWoCdList = stringToArray(searchData.upcWoCdList, /[\n\r]/)
      return searchData
    },
    async queryData() {
      try {
        this.$refs.addSpuSearchHeadRef.searchLoading = true
        const { result } = await addSpuListData(this.handleData())
        if (!result) return
        this.dataList = result.skuBaseInfoAdapterRespList || []
        this.total = result.totalSize
      } finally {
        this.$refs.addSpuSearchHeadRef.searchLoading = false
      }
    },
    async search(isInitalData = false) {
      try {
        if (isInitalData) this.initalData()
        this.$refs.essTableRef.clearSelection()
        this.$refs.addSpuSearchHeadRef.resetLoading = true
        await this.queryData()
      } finally {
        this.$refs.addSpuSearchHeadRef.resetLoading = false
      }
    },
    selectionChange(val) {
      this.multipleSelection = val
    },
    writeSpuName() {
      this.formData.upcList = this.multipleSelection.map((_) => _.upcNbr)
      this.$refs.wirteSpuNameRef.dialogVisible = true
    },
    verificationInfo() {
      this.verificationStatus = true
      this.isVerification = true
      this.getVerificationInfoRequest()
      this.interval = setInterval(this.getVerificationInfoRequest, 2000)
    },
    async getVerificationInfoRequest() {
      try {
        const params = {
          spuId: this.formData.spuId - 0
        }
        const { result } = await getVerificationInfo(params)
        if (!result) return
        this.dataList = result.skuInfoList || []
        // this.formData = { spuName: result.spuName || '', remark: result.remark || '' }
        this.formData.spuName = result.spuName || this.formData.spuName || ''
        this.formData.remark = result.remark || this.formData.remark || ''
        if (result.spuProcessStatus && result.spuProcessStatus.mainStatus) {
          const status = result.spuProcessStatus.mainStatus
          if (status === 101) return
          else if (status === 102) {
            window.clearInterval(this.interval)
            this.verificationStatus = false
          } else if (status === 201) {
            const query = {}
            if (this.menuName) {
              query.menuName = this.menuName
            }
            this.$router.push({
              path: `/spuSeries/${this.formData.spuId}/${status}/${this.$route.name}`,
              query
            })
            this.handleClose()
          }
        }
        // eslint-disable-next-line no-empty
      } catch (error) {
        window.clearInterval(this.interval)
      }
    },

    addUpc() {
      this.$confirm('确认添加, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.addUpcRequest()
        })
        .catch(() => {})
    },
    async addUpcRequest() {
      try {
        this.loading = true
        const data = {
          [this.increased ? 'spuId' : 'chgSpuId']: this.spuId,
          upc: this.multipleSelection[0].upcNbr
        }
        const list = this.skuInfoList
        const checkResult = list.some((_) => _.upcNbr === data.upc)
        if (checkResult) {
          this.$message({
            type: 'error',
            message: 'SPU已存在该商品，请重新选择'
          })
          return
        }
        const requestFun = this.increased ? addSpuSkuMapping : addChgSpuSkuMapping
        const { result } = await requestFun(data)
        if (!result) return
        this.$emit('addSuccess', this.multipleSelection[0])
        this.$message({
          type: 'success',
          message: '添加成功'
        })
        this.handleClose()
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
/deep/ .el-dialog__body {
  padding: 10px 20px;
  height: 75vh;
}
/deep/ .send-spu {
  margin-bottom: 10px !important;
}
</style>
